<template>
  <div id="login">
    <div id="map" style="display:none"></div>
    <div class="logo">
      <img src="@/assets/imgs/logo.png" />
    </div>
    <div class="input-field">
      <md-field class="phone-input radius-border">
        <md-field-item class="radius-border">
          <md-input-item
            name="phone"
            data-vv-name="手机号"
            ref="phoneInput"
            v-model="form.user_phone"
            v-validate="'required|phone'"
            placeholder="请输入您的手机号"
            @blur="phoneBlur"
            :maxlength="11"
            type="phone"
          >
            <md-icon name="telphone_icon" slot="left"></md-icon>
            <md-icon
              name="clear_icon"
              slot="right"
              v-show="form.user_phone!=''"
              @click="clearUserPhone"
            ></md-icon>
          </md-input-item>
        </md-field-item>
      </md-field>
      <md-field class="password-input radius-border" v-show="loginMode=='password'">
        <md-field-item class="radius-border">
          <md-input-item
            name="password"
            data-vv-name="密码"
            v-model="form.password"
            ref="passwordInput"
            placeholder="请输入您的密码"
            type="password"
            v-validate="{required:loginMode=='password'}"
          >
            <md-icon name="mima_icon" slot="left"></md-icon>
          </md-input-item>
        </md-field-item>
      </md-field>
      <md-field class="verify-input radius-border" v-show="loginMode=='captcha'">
        <md-field-item class="radius-border">
          <md-input-item
            name="captcha"
            data-vv-name="验证码"
            ref="captchaInput"
            v-model="form.mobileCode"
            placeholder="请输入短信验证码"
            :maxlength="6"
            type="digit"
            v-validate="loginMode=='captcha'?'required|captcha':''"
          >
            <md-icon name="yzm_icon" slot="left"></md-icon>
            <md-button
              class="get-code-button"
              slot="right"
              @click="getCaptcha"
              size="small"
            >获取验证码</md-button>
          </md-input-item>
        </md-field-item>
      </md-field>
    </div>
    <div class="change-mode-contaienr">
      <div v-if="loginMode=='captcha'"></div>
      <div v-if="loginMode=='captcha'" @click="changePasswordMode">密码登录</div>
      <div v-if="loginMode=='password'" @click="changeCaptchaMode">验证码登录</div>
      <div v-if="loginMode=='password'" @click="forgotPassword">忘记登录密码</div>
    </div>
    <div class="login-button-container">
      <md-button class="login-button" @click="login">登录</md-button>
    </div>
    <div class="agree-container">
      <div>
        登录即代表阅读并同意
        <router-link to="/useragreement">《平安到家用户服务协议》</router-link>和
        <router-link to="/options/privacy">《隐私政策》</router-link>
      </div>
    </div>
    <div class="register-container">
      <div class="register-text">
        还没有账号？
        <span style="color:#FF6917" @click="goRegister">去注册</span>
      </div>
    </div>
    <md-captcha
      ref="captcha"
      v-model="captcha.show"
      title="输入验证码"
      :maxlength="captcha.limit"
      :system="false"
      :mask="false"
      :appendTo="captcha.appendTo"
      @submit="onCaptchaSubmit"
      @show="onCaptchaShow"
      @hide="onCaptchaHide"
      @send="onCaptchaSend"
    >{{captcha.content}}</md-captcha>
  </div>
</template>

<script>
import '@/assets/svgs/telphone_icon.svg';
import '@/assets/svgs/yzm_icon.svg';
import '@/assets/svgs/mima_icon.svg';
import '@/assets/svgs/clear_icon.svg';
import { mapState, mapActions, mapGetters } from 'vuex';
import { LOGIN, GET_CAPTCHA, GET_CURRENT_LOCATION } from '@/store/actions.types';
import {
  GET_CAPTCHA_SUCCESS,
  GET_CAPTCHA_FAILED,
  SET_START_CITY_OBJ
} from '@/store/mutations.types';
import {
  Agree,
  Field,
  InputItem,
  FieldItem,
  Button,
  Toast,
  Icon,
  Captcha,
  Dialog
} from 'mand-mobile';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import http from '@/common/http';
import Loading from '@/components/loading';
const CAPTCHA_MODE = 'captcha';
const PASSWORD_MODE = 'password';
const CAPTCHA_COUNT_DOWN = 60;
export default {
  name: 'Login',
  data() {
    return {
      agreed: true,
      loginMode: CAPTCHA_MODE,
      loginUrl: '',
      form: {
        user_phone: '',
        mobileCode: undefined,
        password: undefined
      },
      captcha: {
        appendTo: document.querySelector('#login'),
        limit: 6,
        show: false,
        content: '请稍后'
      },
      iscaptcha: false
    };
  },
  components: {
    [InputItem.name]: InputItem,
    [Field.name]: Field,
    [FieldItem.name]: FieldItem,
    [Agree.name]: Agree,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Captcha.name]: Captcha,
    [Toast.name]: Toast,
    [Dialog.name]: Dialog
  },
  created() {
    console.log('当前GPS状态', this.gpsStatus);
    if (this.gpsStatus === '0') {
      this.$store
        .dispatch(GET_CURRENT_LOCATION)
        .then(() => {
          let city = {
            start_route: this.getCurrentLocation.provinceName,
            type: '1'
          };
          this.$store.commit(SET_START_CITY_OBJ, city);
        })
        .catch(reason => {
          console.error('当前浏览器没有位置权限', reason.message);
        });
    }
  },
  methods: {
    clearUserPhone() {
      this.form.user_phone = '';
    },
    // 去注册
    goRegister() {
      this.$router.push({
        name: 'Register',
        query: {
          myId: this.$route.query.myId
        }
      });
    },
    getCaptcha() {
      this.$validator.validateAll().then(res => {
        if (this.errors.has('手机号')) {
          Toast({
            content: this.errors.first('手机号'),
            duration: 3000,
            hasMask: false
          });
        } else {
          this.captcha.show = true;
          if (this.iscaptcha) {
            this.onCaptchaSend();
          }
        }
      });
    },
    onCaptchaSubmit(code) {
      console.log('Captcha Submit:', code);
      this.form.mobileCode = code;
      this.login();
    },
    onCaptchaShow() {
      console.log('Captcha Show');
    },
    onCaptchaHide() {
      console.log('Captcha Hide');
      this.resetCaptcha();
    },
    resetCaptcha() {
      this.$refs.captcha.setError('');
      this.$refs.captcha.countdown();
      this.captcha.content = '';
    },
    onCaptchaSend() {
      this.iscaptcha = true;
      this.form.type = '3';
      this.$store.dispatch(GET_CAPTCHA, this.form).then(result => {
        if (result[0] === GET_CAPTCHA_FAILED) {
          console.log(result);
          this.$refs.captcha.setError(result[1]);
          this.$refs.captcha.count = 0;
          this.captcha.content = '';
        } else {
          this.$refs.captcha.count = 60;
          this.captcha.content = '验证码已发送至 ' + this.form.user_phone;
        }
      });
    },
    changeCaptchaMode() {
      this.loginMode = CAPTCHA_MODE;
      this.form.password = undefined;
    },
    changePasswordMode() {
      this.loginMode = PASSWORD_MODE;
      this.form.mobileCode = undefined;
    },
    forgotPassword() {
      this.$router.push({
        name: 'FindPassword'
      });
    },
    // 密码登录时手机号框失去焦点
    phoneBlur() {
      if (this.loginMode === PASSWORD_MODE) {
        this.$validator.validateAll().then(res => {
          if (this.errors.has('手机号')) {
            return false;
          } else {
            var data = {
              user_phone: encryptByDESModeEBC(this.form.user_phone)
            };
            Loading.show();
            http.post('pakj/passenger/getUserByPhone', data).then(res => {
              Loading.hide();
              if (res.data.code === '000000') {
                console.log(res.data);
                if (res.data.data.is_reg === '1') {
                  Dialog.confirm({
                    title: '账号未注册',
                    content: '当前手机号未注册，请注册账号',
                    confirmText: '去注册',
                    onConfirm: () => {
                      this.$router.push({
                        name: 'Register',
                        query: {
                          myId: this.$route.query.myId
                        }
                      });
                    }
                  });
                } else {
                  if (res.data.data.is_login_pwd === '0') {
                    // 登录密码未设置
                    Dialog.alert({
                      title: '设置密码',
                      content: '当前账户未设置登录密码，为保护用户信息安全，需要设置登录密码。',
                      confirmText: '去设置',
                      onConfirm: () => {
                        sessionStorage['login_phone'] = this.form.user_phone;
                        this.$router.push({
                          name: 'SetLoginPwd'
                        });
                      }
                    });
                  }
                }
              } else {
                Dialog.alert({
                  title: '提示',
                  content: res.data.msg,
                  confirmText: '确定'
                });
              }
            });
          }
        });
      }
    },
    login() {
      if (!this.agreed) {
        Dialog.alert({
          content: '请阅读并同意《用户服务协议》',
          confirmText: '确定'
        });
        return;
      }
      this.$validator.validateAll().then(res => {
        console.log(res);
        if (!res) {
          Toast({
            content: this.errors.all()[0],
            duration: 3000,
            hasMask: true
          });
        } else {
          if (this.loginMode === CAPTCHA_MODE) {
            this.form.url = '/pakj/wexin/login';
          } else {
            this.form.url = '/pakj/wexin/loginByPwd';
          }
          this.$store
            .dispatch(LOGIN, this.form)
            .then(() => {
              let query = this.$route.query;
              let next = {
                name: 'Home'
              };
              if (query.next) {
                next.name = query.next;
                delete query.next;
                next.query = query;
              }
              this.$router.replace(next);
            })
            .catch(error => {
              let str = error.toString().split(':');
              let code = str[1].trim();
              console.log(error);
              let msgText = str[2];
              if (code === '200021') {
                Dialog.confirm({
                  title: '账号未注册',
                  content: '当前手机号未注册，请注册账号',
                  confirmText: '去注册',
                  onConfirm: () => {
                    this.$router.push({
                      name: 'Register',
                      query: {
                        myId: this.$route.query.myId
                      }
                    });
                  }
                });
              } else if (code === '100099') {
                var loginerror = JSON.parse(sessionStorage['loginerror']);
                Dialog.confirm({
                  title: loginerror.title,
                  content: loginerror.content,
                  confirmText: '联系客服',
                  onConfirm: () => {
                    if (loginerror.type === '1') {
                      window.location.href = loginerror.url;
                    } else {
                      window.location.href = 'tel://' + loginerror.phone;
                    }
                  }
                });
              } else if (code === '200020') {
                // 密码登录未设置登录密码
                Dialog.confirm({
                  title: '设置密码',
                  content: '当前账户未设置登录密码，为保护用户信息安全，需要设置登录密码。',
                  confirmText: '去设置',
                  onConfirm: () => {
                    sessionStorage['login_phone'] = this.form.user_phone;
                    this.$router.push({
                      name: 'SetLoginPwd'
                    });
                  }
                });
              }
            });
        }
      });
    }
  },
  computed: {
    ...mapGetters(['gpsStatus'])
  }
};
</script>

<style lang="stylus">
login-margin() {
  margin-left: 56px;
  margin-right: 54px;
}

#login {
  width: 100vw;
  background-color: #FFFFFF;
  text-align: center;

  a {
    color: color-primary;
  }

  .logo {
    padding-top: 120px;
    padding-bottom: 100px;

    img {
      width: 180px;
    }
  }

  .input-field {
    login-margin();
    margin-bottom: 12px;

    .md-field-item-inner {
      padding: 0 0;
    }

    .md-field-item {
      padding: 0 0;
    }

    .md-input-item {
      padding: 0 0;

      ::-moz-placeholder {
        color: color-text-caption;
      }

      ::-webkit-input-placeholder {
        color: color-text-caption;
      }

      :-ms-input-placeholder {
        color: color-text-caption;
      }
    }

    .radius-border {
      border-radius: 10px;
    }

    .phone-input {
      margin-bottom: 10px;
    }
  }

  .get-code-button {
    min-width: 170px;
    height: 48px;
    font-size: 22px;
    margin-right: 110px;
    text-align: center;
  }

  .login-button-container {
    login-margin();
    margin-top: 48px;
  }

  .change-mode-contaienr {
    login-margin();
    display: flex;
    justify-content: space-between;

    div {
      font-size: 24px;
      color: color-text-caption;
    }
  }

  .agree-container {
    login-margin();
    margin-top: 14px;

    div {
      font-size: 22px;
      text-align: left;
      color: color-text-caption;
    }
  }

  .register-container {
    login-margin();
    margin-top: 380px;

    .register-text {
      font-size: 24px;
      color: color-text-caption;
    }
  }
}
</style>
